const validate = require('../../utils/validate')
const common = require('../../utils/common')
const {
  locationProvince,
  locationCity,
  locationDistrict,
  locationStreet,
  locationSave
} = require('../../services/location')

Page({
  data: {
    submitInfo: {
      provinceName: '',
      provinceId: '',
      cityName: '',
      cityId: '',
      districtName: '',
      districtId: '',
      streetName: '',
      streetId: '',
      address: '',
      latitude: '',
      longitude: '',
      mapName: '',
    },
    isSureEnable: false,
    provinceList: [],
    cityList: null, //根据省id存储市数组,二维数组与map互换
    selectedCityList: [],
    districtList: null, //根据省id存储县区数组,二维数组与map互换
    selectedDistrictList: [],
    streetList: null, //根据省id存储县区数组,二维数组与map互换
    selectedStreetList: [],
    indexInfo: { //记录当前选择的index
      provinceIndex: 0,
      cityIndex: 0,
      districtIndex: 0,
      streetIndex: 0
    },
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //1.禁止转发
    wx.hideShareMenu();
    this.initData(options.payload)
  },
  initData: function (payload) {
    if (!payload) {
      this.requestToGetLocationProvince()
      return
    }
    const submitInfo = JSON.parse(payload)
    this.setData({
      submitInfo: {
        ...this.data.submitInfo,
        ...submitInfo
      }
    }, this.requestToGetLocationProvince)
  },
  // getRelatedData: async function () {

  // },
  //获取省市
  requestToGetLocationProvince: function () {
    locationProvince().then(res => {
      this.handleLocationProvinceData(res);
      const {
        provinceId
      } = this.data.submitInfo
      this.requestToGetLocationCity(provinceId)
    }).catch(err => {
      common.log(err);
    });
  },
  handleLocationProvinceData: function (res) {
    let provinceList = res.data;
    if (provinceList.length > 0) {
      this.setData({
        provinceList
      }, () => {
        this.checkCanSubmit()
        this.getIndexInfo()
      });
    } else {
      common.showToast(res.message);
    }
  },

  //获取市
  requestToGetLocationCity: function (provinceId) {
    if (!provinceId) return
    return locationCity({
      provinceId
    }).then(res => {
      this.handleLocationCityData(res, provinceId);
      const {
        cityId
      } = this.data.submitInfo
      this.requestToGetLocationDistrict(cityId)
    }).catch(err => {
      common.log(err);
    });
  },

  //处理市信息
  handleLocationCityData: function (res, provinceId) {
    let tempList = res.data;
    if (tempList.length > 0) {
      this.setData({
        selectedCityList: tempList,
      }, () => {
        this.checkCanSubmit()
        this.getIndexInfo()
      });
    } else {
      common.showToast(res.message);
    }
  },

  //根据市去获取区县
  requestToGetLocationDistrict: function (cityId) {
    if (!cityId) return
    return locationDistrict({
      cityId
    }).then(res => {
      this.handleLocationDistrictData(res, cityId);
      const {
        districtId
      } = this.data.submitInfo
      this.requestToGetLocationStreet(districtId)
    }).catch(err => {
      common.log(err);
    });
  },

  //处理获取到的区县信息
  handleLocationDistrictData: function (res, cityId) {
    let tempList = res.data;
    if (tempList.length > 0) {
      this.setData({
        selectedDistrictList: tempList,
      }, () => {
        this.checkCanSubmit()
        this.getIndexInfo()
      });
    } else {
      common.showToast(res.message);
    }
  },

  //根据区县获取街道
  requestToGetLocationStreet: function (districtId) {
    if (!districtId) return
    return locationStreet({
      districtId
    }).then(res => {
      this.handleLocationStreetData(res, districtId);
    }).catch(err => {
      common.log(err);
    });
  },

  //处理获取到的街道信息
  handleLocationStreetData: function (res, districtId) {
    let tempList = res.data;
    if (tempList.length > 0) {
      this.setData({
        selectedStreetList: tempList,
      }, () => {
        this.checkCanSubmit()
        this.getIndexInfo()
      });
    } else {
      common.showToast(res.message);
    }
  },

  getIndexInfo: function () {
    const {
      provinceId,
      cityId,
      districtId,
      streetId
    } = this.data.submitInfo
    const provinceIndex = this.data.provinceList.findIndex(v => v.id == provinceId) || 0
    const cityIndex = this.data.selectedCityList.findIndex(v => v.id == cityId) || 0
    const districtIndex = this.data.selectedDistrictList.findIndex(v => v.id == districtId) || 0
    const streetIndex = this.data.selectedStreetList.findIndex(v => v.id == streetId) || 0
    const indexInfo = {
      provinceIndex,
      cityIndex,
      districtIndex,
      streetIndex,
    }
    if (indexInfo.provinceIndex == -1 || indexInfo.cityIndex == -1 || indexInfo.districtIndex == -1  || indexInfo.streetIndex == -1 ) return;
    this.setData({
      indexInfo,
    })
  },
  //省市选择
  onProvinceChange: function (e) {
    const index = parseInt(e.detail.value);
    const item = this.data.provinceList[index];
    const submitInfo = {
      ...this.data.submitInfo,
      provinceName: item.name,
      provinceId: item.id,
      cityName: '',
      cityId: '',
      districtName: '',
      districtId: '',
      streetName: '',
      streetId: '',
      address: '',
    };
    this.setData({
      submitInfo
    });
    //根据省去获取市
    this.requestToGetLocationCity(item.id);
  },

  //市辖市
  onCityChange: function (e) {
    const index = parseInt(e.detail.value);
    const item = this.data.selectedCityList[index];
    const submitInfo = {
      ...this.data.submitInfo,
      cityName: item.name,
      cityId: item.id,
      districtName: '',
      districtId: '',
      streetName: '',
      streetId: '',
      address: '',
    };
    this.setData({
      submitInfo
    });
    //根据市去获取县区
    this.requestToGetLocationDistrict(item.id);
  },

  //县区选择
  onDistrictChange: function (e) {
    const index = parseInt(e.detail.value);
    const item = this.data.selectedDistrictList[index];
    const submitInfo = {
      ...this.data.submitInfo,
      districtName: item.name,
      districtId: item.id,
      streetName: '',
      streetId: '',
      address: '',
    };
    this.setData({
      submitInfo
    });
    //根据区县去获取街道
    this.requestToGetLocationStreet(item.id);
  },

  //街道
  onStreetChange: function (e) {
    const index = parseInt(e.detail.value);
    const item = this.data.selectedStreetList[index];
    const submitInfo = {
      ...this.data.submitInfo,
      streetName: item.name,
      streetId: item.id,
      address: '',
    };
    this.setData({
      submitInfo
    }, () => {
      this.checkCanSubmit()
      this.getIndexInfo()
    });
  },

  checkCanSubmit: function () {
    const {
      provinceId,
      cityId,
      districtId,
      streetId,
      address
    } = this.data.submitInfo
    let isSureEnable = false
    if (provinceId && cityId && districtId && streetId && address) {
      isSureEnable = true
    } else {
      isSureEnable = false
    }
    this.setData({
      isSureEnable
    })
    return isSureEnable
  },
  //详细地址
  onDeailAddress: function (e) {
    this.autherToOpenMap();
  },

  //地图选择之后设置详细地址
  updateDetailAddress: function (res) {
    var tmp = res.address;
    var tmpSubmitInfo = this.data.submitInfo;
    tmpSubmitInfo.address = tmp;
    tmpSubmitInfo.latitude = res.latitude;
    tmpSubmitInfo.longitude = res.longitude;
    tmpSubmitInfo.mapName = res.name;
    this.setData({
      submitInfo: tmpSubmitInfo
    }, this.checkCanSubmit);
  },

  //授权打开地图
  autherToOpenMap: function () {
    if (wx.getLocation) {
      //1.获取设置
      wx.getSetting({
        success: res => {
          if (!res.authSetting['scope.userLocation']) {
            //2.提前授权
            wx.authorize({
              scope: 'scope.userLocation',
              success: res => {
                //3.获取经纬度
                wx.getLocation({
                  type: 'gcj02',
                  success: res => {
                    this.openWechatLocation(res);
                  }
                })
              },
              fail: res => {
                //拒绝授权
                this.handleMapFailAuthDeny(res);
              }
            })
          } else {
            //3.获取经纬度
            wx.getLocation({
              type: 'gcj02',
              success: res => {
                this.openWechatLocation(res);
              }
            });
          }
        }
      })
    } else {
      common.showModal("当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。");
    }
  },

  //处理拒绝地图授权
  handleMapFailAuthDeny: function (res) {
    //授权拒绝
    var firstAuthDeny = res.errMsg.indexOf("fail auth deny") != -1;
    if (firstAuthDeny) return;
    //提示打开设置
    common.showModal({
      content: "亲，我们未获得您的位置授权，即将打开设置",
      showCancel: true
    }, () => {
      wx.openSetting({
        success: res => {
          var isOpenUserLocation = res.authSetting['scope.userLocation'];
          // 选择自提点
          if (isOpenUserLocation) {
            this.autherToOpenMap();
          }
        }
      })
    });
  },

  //打开微信内置地图
  openWechatLocation: function (res) {
    const latitude = res.latitude;
    const longitude = res.longitude;
    //2.打开地图选择位置
    wx.chooseLocation({
      latitude: latitude,
      longitude: longitude,
      success: res => {
        //1.设置参数
        this.updateDetailAddress(res);
      }
    });
  },

  //确定
  onSure: function () {
    //调用方法，返回上一页
    var pages = getCurrentPages();
    var prePage = pages[pages.length - 2];
    prePage.updateAddress(this.data.submitInfo);
    //返回
    wx.navigateBack({});
  }
})
